package com.glgc.projecti.common;

import org.springframework.util.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author zhongming
 *
 */
public class HttpRequestTool {

    private HttpRequestTool() {

    }

    public static String httpsRequest(String requestUrl, String requestMethod,
                                      String outputStr) {

        StringBuilder respStrData = new StringBuilder();

        try {

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
                    .openConnection();
            // httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            httpUrlConn.setRequestMethod(requestMethod);
            httpUrlConn.connect();

            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str;
            while ((str = bufferedReader.readLine()) != null) {
                respStrData.append(str);
            }

            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            httpUrlConn.disconnect();

        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return respStrData.toString();
    }

    public static Map<String, Object> getUrlParams(String param) {
        Map<String, Object> map = new HashMap<String, Object>(0);
        if (StringUtils.isEmpty(param)) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }else if (p.length == 1) {
                map.put(p[0], "");
            }
        }
        return map;
    }

    public static String getUrlParamsByMap(Map<String, Object> map) throws UnsupportedEncodingException {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + URLEncoder.encode((String) entry.getValue(), "UTF-8"));
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = org.apache.commons.lang.StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }

    public static void main(String[] args) throws UnsupportedEncodingException, BizException {
        String s = "http://61.160.96.18/HTTPCHANNEL/HSSERVICE?funcno=991001&appid=&sign=&user_name=徐宏辉&activity_id=9001&funcno=8991001&mobile_tel=13771615365&fund_account=11235464&wechat_id=oBnVUs3LdMRmVTIw8rzsUAcVM8Jw";

        String httpurl = s.substring(0,s.indexOf("?")+1) ;
        String urlparam = s.substring(s.indexOf("?")+1) ;
        System.out.println(httpurl+getUrlParamsByMap(getUrlParams(urlparam)));


        System.out.println(httpRequest(s,"GET",null));
    }
    public static String httpRequest(String requestUrl, String requestMethod,
                                     String outputStr) throws BizException   {

        String httpurl =requestUrl.substring(0,requestUrl.indexOf("?")+1) ;
        String urlparam = requestUrl.substring(requestUrl.indexOf("?")+1) ;
        try {
            requestUrl = httpurl+getUrlParamsByMap(getUrlParams(urlparam));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        StringBuilder respStrData = new StringBuilder();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url
                    .openConnection();

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);
            httpUrlConn.connect();
            int responseCode = httpUrlConn.getResponseCode();
            if (responseCode == 500) {
            	throw new BizException(
            			httpUrlConn.getHeaderFields().get("ERROR_CODE").get(0), 
            			httpUrlConn.getHeaderFields().get("ERROR_TIP").get(0), "remote server 500 error");
            }
            // 当有数据需要提交时
           /* outputStr = outputStr == null ? "" : outputStr;
            OutputStream outputStream = httpUrlConn.getOutputStream();
            // outputStream.write(outputStr.getBytes(Constants.CHARACTER_ENCODING_UTF8));
            outputStream.close();*/

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            // InputStreamReader inputStreamReader = new
            // InputStreamReader(inputStream,
            // Constants.CHARACTER_ENCODING_UTF8);
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream,"UTF-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str;
            while ((str = bufferedReader.readLine()) != null) {
                respStrData.append(str);
            }

            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            httpUrlConn.disconnect();
        } catch (BizException be) {
            throw be;
        } catch (Exception e) {
            throw new BizException("remote server error", e);
        }

        return respStrData.toString();
    }
}
